<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span
          ><my-bread>{{
            $route.query.id ? "编辑文章" : "发布文章"
          }}</my-bread></span
        >
      </div>
      <!-- 表单 -->
      <el-form
        ref="form"
        :model="form"
        :rules="articleRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="form.content"
            :options="editorOption"
            @blur="changeContent"
          />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-radio-group
            v-model="form.cover.type"
            @change="form.cover.images = []"
          >
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <!-- <br> -->
          <!-- 封装按钮组件 -->
          <!-- <my-cover v-for="i in 3" :key="i"></my-cover> -->
          <!-- <div><my-cover v-for="i in 3" :key="i"></my-cover></div> -->
          <div v-if="form.cover.type === 1 || form.cover.type === 3">
            <my-cover
              v-for="i in form.cover.type"
              :key="i"
              v-model="form.cover.images[i - 1]"
              @on-comfirm="checkCover"
            ></my-cover>
          </div>
        </el-form-item>
        <!-- <my-cover v-for="i in 3" :key="i"></my-cover> -->

        <el-form-item label="频道" prop="channel_id">
          <my-channel v-model="form.channel_id"></my-channel>
        </el-form-item>
        <el-form-item label="" v-if="$route.query.id">
          <el-button type="success" @click="editArticle">修改文章</el-button>
        </el-form-item>
        <el-form-item label="" v-else>
          <el-button type="primary" @click="addArticle(false)"
            >发布文章</el-button
          >
          <el-button @click="addArticle(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  watch: {
    '$route.query.id' () {
      if (this.$route.query.id) {
        this.getArticle()
      } else {
        // this.$refs.form.resetFields()
        this.$refs.form.resetFields()
      }
    }
  },
  name: 'my-article',
  components: { quillEditor },
  created () {
    if (this.$route.query.id) {
      this.getArticle()
    }
  },
  data () {
    const checkCoverFn = (rule, value, callback) => {
      console.log(value)
      if (value.type === 1) {
        if (!value.images[0]) {
          return callback(new Error('请选择一张照片'))
        }
      }
      if (value.type === 3) {
        if (!(value.images[0] && value.images[1] && value.images[2])) {
          return callback(new Error('请选择三张照片'))
        }
      }
      callback()
    }
    return {
      articleRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50个字符', trigger: 'blur' }
        ],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        channel_id: [
          { required: true, message: '请输入内容', trigger: 'change' }
        ],
        cover: [{ validator: checkCoverFn, trigger: 'change' }]
      },
      editorOption: {
        placeholder: '请输入文章内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      form: {
        title: null,
        content: null,
        cover: {
          type: 1,
          images: []
        },
        channel_id: null
      }
    }
  },
  methods: {
    editArticle () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //  发请求
          try {
            await this.$http.put('/mp/v1_0/articles/' + this.$route.query.id, this.form)
            this.$message.success('修改文章成功')
            this.$router.push('/content')
          } catch {
            (e) => {
              this.$message.error('修改失败')
            }
          }
        }
      })
    },
    // 获取文章详情
    async getArticle () {
      const {
        data: { data }
      } = await this.$http.get('/mp/v1_0/articles/' + this.$route.query.id)
      this.form = data
    },
    addArticle (draft) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //  发请求
          try {
            const res = await this.$http.post(
              '/mp/v1_0/articles?draft=' + draft,
              this.form
            )
            this.$message.success(draft ? '存入草稿 成功' : '发布文章成功')
            this.$router.push('/content')
          } catch {
            (e) => {
              this.$message.error(draft ? '存入草稿失败' : '发布文章失败')
            }
          }
        }
      })
    },
    changeContent () {
      this.$refs.form.validateField('content')
      //  this.$refs.form.validateField((content) => {
      //     if (content) {
      //       alert('submit!');
      //     } else {
      //       console.log('error submit!!');
      //       alert('submitsssssssssssss!');
      //       return false;
      //     }
      //   });
    },
    checkCover () {
      this.$refs.form.validateField('cover')
    }
  }
}
</script>

<style scoped lang='less'>
::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}
::v-deep .ql-editor {
  height: 200px;
}
</style>
